package raft

import (
    "fmt"
)

// PeerClient 模拟 RPC 远程节点
type PeerClient struct {
    Node *Raft
}

type AppendEntriesArgs struct {
    Term         int
    LeaderID     int
    PrevLogIndex int
    PrevLogTerm  int
    Entries      []LogEntry
    LeaderCommit int
}

type AppendEntriesReply struct {
    Term    int
    Success bool
}

// AppendEntries 处理 AppendEntries RPC 请求
func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) error {
    rf.mu.Lock()
    defer rf.mu.Unlock()

    if args.Term < rf.currentTerm {
        reply.Term = rf.currentTerm
        reply.Success = false
        return nil
    }

    if args.Term > rf.currentTerm {
        rf.convertToFollower(args.Term)
    }

    if args.PrevLogIndex >= len(rf.log) || rf.log[args.PrevLogIndex].Term != args.PrevLogTerm {
        reply.Success = false
        return nil
    }

    rf.log = append(rf.log[:args.PrevLogIndex+1], args.Entries...)
    if args.LeaderCommit > rf.commitIndex {
        rf.commitIndex = min(args.LeaderCommit, len(rf.log)-1)
    }

    reply.Success = true
    return nil
}

// sendAppendEntries 发送 AppendEntries RPC 请求
func (rf *Raft) sendAppendEntries(peer *PeerClient, args *AppendEntriesArgs, reply *AppendEntriesReply) bool {
    err := peer.Node.AppendEntries(args, reply)
    if err != nil {
        fmt.Println("AppendEntries RPC failed:", err)
        return false
    }
    return true
}

// min 返回两个整数中的较小值
func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}
